<?php
abstract class RestHandler{

	private $log;
	protected $status, $message, $content_type, $header, $body;
	protected $method;
	protected $requestData, $responseObject;
	protected $requestHeader;
	protected $secure = array('GET' => false,'POST' => false);

	function __construct(){
		$this->log = new Logger("RestHandler", _LOGPATH_);
		$this->log->setLogLevel(Logger::VERBOSE);
		$this->status = 501;
		$this->content_type		= (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'json')) ? 'application/json' : 'application/xml';
		$this->method = isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:"GET";
		$this->requestHeader = apache_request_headers();
	}

	public function processRequest(){
		$this->log->debug("start handling ".$this->method." request");

		$this->data			= array();

		if($this->secure[$this->method] && !$this->validate()){
			$this->status = 401;
			return;
		}


		switch ($this->method){
			case 'GET':
				$this->requestData	 = $_GET;
				$this->processGetRequest();
				break;
			case 'POST':
				$this->requestData	 = $_POST;
				$this->processPostRequest();
				break;
			case 'OPTIONS':
				$this->status = 200;
		}
	}

	public function setStatus($status){
		$this->status = $status;
	}

	public function sendResponse(){
		$this->message = Util::getStatusCodeMessage($this->status);
		if ($this->responseObject != "") {
			$this->createBody();
		}

		$this->header = 'HTTP/1.1 ' . $this->status . ' ' . $this->message;
		header($this->header);
		header("Content-Type: ".$this->content_type);
		header("Access-Control-Allow-Origin: *");
		header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
		header("Access-Control-Allow-Headers: Authorization");


		$this->log->debug("sending NOW; Header: $this->header");
		print $this->body;
	}

	private function createBody(){
		//switch/case für XML?
		$this->log->debug("creating body, accepted MIME-type is: $this->content_type");

		if($this->content_type=="application/json"){
			$this->log->verbose("converting object to jsonObject");
			$jsonObject = json_encode($this->responseObject);
			$this->body = $jsonObject;
		}else if($this->content_type=="application/xml"){
			$this->log->verbose("converting object to xmlObject");
			$serializer = new Serializer();
			$xmlObject = $serializer->encode($this->responseObject);
			$this->body = $xmlObject;
		}else{
			$this->status = 500;
		}
	}

	public abstract function processGetRequest();
	public abstract function processPostRequest();
	public abstract function validate();
}

class RestHandlerTable{

}
